<!doctype html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>






<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="LintCode,算法," />








  <link rel="shortcut icon" type="image/x-icon" href="/uploads/images/logo/favicon.ico?v=5.1.1" />






<meta name="description" content="我是小小强，这是我的第6篇原创文章，阅读需要大约10分钟。    题目LintCode:二进制求和 描述给定两个二进制字符串，返回他们的和（用二进制表示）。 样例a = 11b = 1返回 100">
<meta name="keywords" content="LintCode,算法">
<meta property="og:type" content="article">
<meta property="og:title" content="[容易]408.二进制求和">
<meta property="og:url" content="http://xiaoxiaoqiang.win/2017/07/01/LintCode/容易-408-二进制求和/index.html">
<meta property="og:site_name" content="小小强的部落">
<meta property="og:description" content="我是小小强，这是我的第6篇原创文章，阅读需要大约10分钟。    题目LintCode:二进制求和 描述给定两个二进制字符串，返回他们的和（用二进制表示）。 样例a = 11b = 1返回 100">
<meta property="og:updated_time" content="2017-07-11T16:07:54.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="[容易]408.二进制求和">
<meta name="twitter:description" content="我是小小强，这是我的第6篇原创文章，阅读需要大约10分钟。    题目LintCode:二进制求和 描述给定两个二进制字符串，返回他们的和（用二进制表示）。 样例a = 11b = 1返回 100">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://xiaoxiaoqiang.win/2017/07/01/LintCode/容易-408-二进制求和/"/>





  <title>[容易]408.二进制求和 | 小小强的部落</title>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">小小强的部落</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">我思故我在</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://xiaoxiaoqiang.win/2017/07/01/LintCode/容易-408-二进制求和/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="小小强">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/images/logo/icon.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小小强的部落">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">[容易]408.二进制求和</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-01T11:36:12+08:00">
                2017-07-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/LintCode/" itemprop="url" rel="index">
                    <span itemprop="name">LintCode</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>我是小小强，这是我的第6篇原创文章，阅读需要大约10分钟。  </p>
<hr>
<h1 id="题目"><a href="#题目" class="headerlink" title="题目"></a>题目</h1><p>LintCode:<a href="http://www.lintcode.com/zh-cn/problem/add-binary/" target="_blank" rel="external">二进制求和</a></p>
<h1 id="描述"><a href="#描述" class="headerlink" title="描述"></a>描述</h1><p>给定两个二进制字符串，返回他们的和（用二进制表示）。</p>
<h1 id="样例"><a href="#样例" class="headerlink" title="样例"></a>样例</h1><p>a = 11<br>b = 1<br>返回 100  </p>
<a id="more"></a>
<h1 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h1><p>二进制相加，主要考虑进位的情况，每位在进行相加之后，要判断之前有无进位的情况，如果有，本位要进行加1处理，同时还要考虑是否要再次向高位进位。相加结果的二进制串长度是有可能超过原数的。<br>最直接的方法将二进制串转换为整数，进行相加，然后将结果再转换为二进制串。</p>
<h1 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h1><h2 id="非递归实现"><a href="#非递归实现" class="headerlink" title="非递归实现"></a>非递归实现</h2><ol>
<li><p>java实现</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div></pre></td><td class="code"><pre><div class="line">public class Solution &#123;</div><div class="line">    /**</div><div class="line">     * @param a a number</div><div class="line">     * @param b a number</div><div class="line">     * @return the result</div><div class="line">     */</div><div class="line">    public String addBinary(String a, String b) &#123;</div><div class="line">        // Write your code here</div><div class="line">        if (a == null || b == null) &#123;</div><div class="line">            return null;</div><div class="line">        &#125;</div><div class="line">        return parseInt2String(parseString2(a) + parseString2(b));</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">     public static int parseString2(String str1)&#123;</div><div class="line">        char c = 0;</div><div class="line">        int sum = 0;</div><div class="line">        for (int i = 0; i &lt; str1.length(); i++) &#123;</div><div class="line">            if (str1.charAt(i) == &apos;1&apos;)&#123;</div><div class="line">                sum += 1&lt;&lt;(str1.length()-1-i);</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">        return sum;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    public static String parseInt2String(int a)&#123;</div><div class="line">        String str = &quot;&quot;;</div><div class="line">        if (a == 0)</div><div class="line">            return &quot;0&quot;;</div><div class="line">        while (a != 0)&#123;</div><div class="line">            str += a % 2;</div><div class="line">            a = a/2;</div><div class="line">        &#125;</div><div class="line">        String str2 = &quot;&quot;;</div><div class="line">        int i = str.length();</div><div class="line">        while (i &gt; 0 )&#123;</div><div class="line">            str2+=str.charAt(i-1);</div><div class="line">            i--;</div><div class="line">        &#125;</div><div class="line">        return str2;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>结果分析<br>结果：结果通过了LintCode的要求。<br>分析：这种实现比较好理解，但是实现起来却没什么巧妙之处。</p>
</li>
</ol>
<h1 id="其它优化参考"><a href="#其它优化参考" class="headerlink" title="其它优化参考"></a>其它优化参考</h1><p><a href="http://blog.csdn.net/cjt5047/article/details/50708902" target="_blank" rel="external">lintcode 二进制求和 给定两个二进制字符串，返回他们的和</a><br><a href="http://blog.csdn.net/sunny_ran/article/details/49054183" target="_blank" rel="external">LIntCode-二进制求和</a><br><a href="https://discuss.leetcode.com/topic/13698/short-ac-solution-in-java-with-explanation" target="_blank" rel="external">Short AC solution in Java with explanation</a></p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/uploads/images/money/wechat.JPG" alt="小小强 WeChat Pay"/>
          <p>微信打赏</p>
        </div>
      
      
        <div id="alipay" style="display: inline-block">
          <img id="alipay_qr" src="/uploads/images/money/ali.JPG" alt="小小强 Alipay"/>
          <p>支付宝打赏</p>
        </div>
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/LintCode/" rel="tag"># LintCode</a>
          
            <a href="/tags/算法/" rel="tag"># 算法</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/06/29/LintCode/入门-366-斐波纳契数列/" rel="next" title="[入门]366.斐波纳契数列">
                <i class="fa fa-chevron-left"></i> [入门]366.斐波纳契数列
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/07/01/LintCode/容易-569-各位相加/" rel="prev" title="[容易]569.各位相加">
                [容易]569.各位相加 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/images/logo/icon.jpg"
               alt="小小强" />
          <p class="site-author-name" itemprop="name">小小强</p>
           
              <p class="site-description motion-element" itemprop="description">技术之路历练</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">18</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">18</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/wayd2001" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.jianshu.com/u/5813fda87ee0" target="_blank" title="JianShu">
                  
                    <i class="fa fa-fw fa-book"></i>
                  
                  JianShu
                </a>
              </span>
            
          
        </div>

        
        
          <div class="cc-license motion-element" itemprop="license">
            <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
              <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
            </a>
          </div>
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.jianshu.com/u/5813fda87ee0" title="小小强简书" target="_blank">小小强简书</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#题目"><span class="nav-number">1.</span> <span class="nav-text">题目</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#描述"><span class="nav-number">2.</span> <span class="nav-text">描述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#样例"><span class="nav-number">3.</span> <span class="nav-text">样例</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#思路"><span class="nav-number">4.</span> <span class="nav-text">思路</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#实现"><span class="nav-number">5.</span> <span class="nav-text">实现</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#非递归实现"><span class="nav-number">5.1.</span> <span class="nav-text">非递归实现</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#其它优化参考"><span class="nav-number">6.</span> <span class="nav-text">其它优化参考</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>

<span id="busuanzi_container_site_uv">
  本站访客数<span id="busuanzi_value_site_uv"></span>人次
</span>


<div class="copyright" >
  
  &copy;  2017 - 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">小小强</span>
</div>



<div class="powered-by">
  由 <a class="theme-link" href="#">小小强</a> 个人专属
</div>

<div class="theme-info">
  博客 -
  <a class="theme-link" href="#">
   小小强
  </a>
</div>
<p>Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a></p>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2138352"></script>
      <!-- UY END -->
    
  





  






  





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  



</body>
</html>
